package csse3004.GD.PM;

import csse3004.GD.DA.PollMasterDA;
import csse3004.GD.Question;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * This class handles the nearly blank currentQuestion page, which is just a 
 * dynamic data-store for both the Admin and the live pages - they fetch it with
 * ajax to avoid having page refreshes
 * @author David Bullock 42062222
 */
public class currentQuestionController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());
    private PollMasterService service = new PollMasterDA();

    public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
        ModelAndView mav = new ModelAndView("currentQuestion");
        try {
            int pid = Integer.parseInt(hsr.getParameter("pid"));

            Question question;
            ArrayList<String> object;
            if (service.database) {
                question = service.getActiveQuestion(Integer.parseInt(hsr.getParameter("pid")));
                object = service.getObjectHTML(pid);
            } else {
                question= new Question().genTestQuestion(pid).get(0);
                object  = new ArrayList<String>();
                object.add("<b>test</b>");
                object.add("test2");
                object.add("test3");
            }

            mav.addObject("question", question);
            mav.addObject("object", object);

            mav.addObject("pid", pid);
            return mav;
        } catch (NumberFormatException E) {
            logger.info("error!!! " + E);
            return new ModelAndView("live");
        }
    }
}
